import django_filters
from django.db.models import Q
from .models import Products


class ProductsFilter(django_filters.FilterSet):
    category = django_filters.CharFilter(
        field_name="short_name", lookup_expr='icontains', label="类别")
    pricegte = django_filters.NumberFilter(
        field_name='price', lookup_expr='gte', label="价格大于")
    boughtgte = django_filters.NumberFilter(
        field_name='bought_last_month', lookup_expr='gte', label="月销量大于")
    anyword = django_filters.CharFilter(method='any_filter', label="综合查询")

    class Meta:
        model = Products
        fields = ['pricegte', 'anyword']

    def any_filter(self, queryset, anyword, value):
        return queryset.filter(Q(name__icontains=value) |
                               Q(short_name__icontains=value) |
                               Q(brand__icontains=value) |
                               Q(seller__icontains=value) |
                               Q(bought_last_month__icontains=value) |
                               Q(conn_tech__icontains=value)
                               )
